package org.opens.lambda.stream.sort;

import com.google.common.collect.ComparisonChain;
import org.junit.Test;
import org.opens.lambda.UserEntity;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListDemo {

    private List<UserEntity> userEntities = UserEntity.getList(5);

    /**
     * 功能:
     *      使排序结果*-1使最终结果按照降序排序.
     */
    @Test
    public void test1() {
        List<UserEntity> collect = userEntities.stream().sorted((v1, v2) -> {
            //将结果乘-1即可使比较器反回相反的结果, 使最终的list以反序进行排序.
            return -1 * ComparisonChain
                    .start()
                    .compare(v1.getId(), v2.getId())
                    .result();
        }).collect(Collectors.toList());
        System.out.println(collect);
    }

    /**
     * 功能:
     *      使List中的元素按照某个字段进行升序排序.
     */
    @Test
    public void test2() {
        List<UserEntity> collect = userEntities.stream().sorted(Comparator.comparingInt(UserEntity::getId)).collect(Collectors.toList());
        System.out.println(collect);
    }

}
